<template>
    <div class="layout-route">
        <div class="card card-search">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                <el-form-item label="订单号" prop="order_id">
                    <el-input type="textarea" :rows="4" v-model="queryParams.order_id" placeholder="请输入订单号" clearable />
                </el-form-item>
                <el-form-item label="物流单号" prop="tracking_number">
                    <el-input type="textarea" :rows="4" v-model="queryParams.tracking_number" placeholder="请输入物流单号" clearable />
                </el-form-item>
                <el-form-item label="创建时间" prop="create_time">
                    <el-date-picker v-model="queryParams.create_time"
                        type="daterange"
                        range-separator="至"
                        @change="handleDateRangeChangec"  
                        start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 240px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="姓名" prop="contact">
                    <el-input v-model.trim="queryParams.contact" placeholder="请输入姓名" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="发货SKU" prop="sku">
                    <el-input v-model.trim="queryParams.sku" placeholder="请输入发货SKU" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain @click="handleModification">手动发货</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="el-icon-download" :loading="download" :disabled="download" @click="handleExport">导出</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="success" plain icon="el-icon-plus" @click="showDetailDialog">录入订单</el-button>
                </el-col>
                <el-col :span="1.5">
                    <upload-button plain :data="{ type: 1 }" :action="action" @complete="getList" text="导入订单"></upload-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="success" plain icon="el-icon-download" :loading="download" :disabled="download" @click="downloadExcel">发货模板</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-tabs v-model="activeTab" @tab-click="handleStatus" type="border-card">
                <el-tab-pane v-for="(item, index) in tabstatus" :key="index" :label="item.label" :name="item.value.toString()"> </el-tab-pane>
                <el-tabs v-model="activeTab2" @tab-click="handleStatus2" type="border-card">
                    <el-tab-pane v-for="(item, index) in type_arr" :key="index" :label="item.label" :name="item.value.toString()"> </el-tab-pane>
                <el-table ref="sortTable" 
                v-loading="loading" :data="tableData" 
                @selection-change="handleSelectionChange"  
                row-key="id" 
                border script @sort-change="handleSortChange">
                    <!-- <el-table-column label="SPU" prop="spu" width="">
                        <template slot-scope="scope">
                            <el-link type="primary" @click="showDetailDialog(scope.row)">{{ scope.row.spu }}</el-link>
                        </template>
                    </el-table-column> -->
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="类型" prop="type_msg" width="80" ></el-table-column>
                    <el-table-column label="日期" prop="created_time" width="120" ></el-table-column>
                    <el-table-column label="姓名" prop="contact" width="120" ></el-table-column>
                    <el-table-column label="仓库" prop="warehouse_name" width="120" ></el-table-column>
                    <!-- <el-table-column label="姓名" prop="deliver_no" width="" ></el-table-column> -->
                    <el-table-column label="状态" prop="status_msg" width="80" ></el-table-column>
                    <el-table-column label="负责人" prop="username" width="80" ></el-table-column>
                    <el-table-column label="发货详情" prop="error" width="80" show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column label="订单号" prop="deliver_no" width="220" ></el-table-column>
                    <el-table-column label="物流单号" prop="waybill_no" width="220" ></el-table-column>
                    <el-table-column v-if="this.queryParams.type ==2" label="达人ID" prop="ExpertId" width="120" ></el-table-column>
                    <el-table-column label="发货SKU" prop="sku" width="120" ></el-table-column>
                    <el-table-column label="电话" prop="mobile" width="120" ></el-table-column>
                    <el-table-column label="详细地址" prop="address" width="120" ></el-table-column>
                    <el-table-column label="省份" prop="city" width="120" ></el-table-column>
                    <el-table-column label="市区" prop="district" width="120" ></el-table-column>
                    <el-table-column label="邮编" prop="zip" width="120" ></el-table-column>
                    <el-table-column label="邮箱" prop="email" width="120" ></el-table-column>
                    
                    <el-table-column label="操作" min-width="80" fixed="right">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.status == 3 || scope.row.status == 0" type="text" icon="el-icon-edit" @click="showDetailDialog(scope.row)">修改</el-button>
                            <el-button v-if="scope.row.status == 2" type="text" icon="el-icon-info" @click="showDetailDialog2(scope.row)">物流轨迹</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tabs>
            </el-tabs>
            <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList" />
        </div>
        <detail-dialog v-model="detailDialog.visible" v-if="detailDialog.visible" :params="detailDialog.data" @success="handleQuery"></detail-dialog>
        <DetailTrackDialog v-model="detailDialog2.visible" v-if="detailDialog2.visible" :params="detailDialog2.data" @success="handleQuery"></DetailTrackDialog>
    </div>
</template>
<script>
import { queryAutoshipping ,exportAutoshipping } from '@/api/order'
import { exportFile } from '@/utils/index'
import { parseTime } from '@/utils/quickadmin'
import DetailDialog from './components/DetailDialog.vue'
import DetailTrackDialog from './components/DetailTrackDialog.vue'
export default {
    name: 'availablestock',
    components: { DetailDialog,DetailTrackDialog },
    data() {
        return {
            type_arr: [
                { label: '全部', value: 'All' },
                { label: '海拍发货', value: "3" },
                { label: 'KOL发货', value: "2" },
                { label: 'TK发货', value: "1" },
                { label: 'Billo', value: "4" },
            ],
            tabstatus: [
                { label: '全部', value: 'All' },
                { label: '等待发货', value: 0 },
                { label: '回传物流单号', value: 1 },
                { label: '发货成功', value: 2 },
                { label: '发货失败', value: 3 },
                { label: '取消发货', value: 4 },
            ],
            activeTab: 'All',
            activeTab2: 'All',
            action: process.env.VUE_APP_BASE_API + '/tiktok/Autoshipping/uploadInventory',
            // 遮罩层
            loading: true,
            download: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            // data中定义Arr数组，用来存放筛选列
            orderArray: [],
            sorts: [], // 用于存储多列排序信息的数组

            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 查询参数
            queryParams: {
                type: undefined,
                status: undefined,
            },
            detailDialog: {
                visible: false,
                data: {},
            },
            detailDialog2: {
                visible: false,
                data: {},
            },
            multipleSelection: [],
            api: {
                //export: `/order/orderdeliver/export`,
                //upload: process.env.VUE_APP_BASE_API + `/order/Orderdeliver/uploads`,
                automatic_shipping: `/tiktok/Autoshipping/automatic_shipping`,
                //MarkAsProcessed: `/order/orderdeliver/MarkAsProcessed`,
            },
            downloadUrl: process.env.VUE_APP_BASE_API + '/storage/system/automatic_shipping.xlsx',
        }
    },
    async created() {
        this.loading = true
        try {
            
        } catch (error) {
            this.loading = false
        }
        this.getList()
    },
    methods: {
        handleSelectionChange(val) {  
            this.multipleSelection = val.map(item => item.id)
        }, 

        handleDateRangeChangec(value) {  
            this.queryParams.create_time = value.map(dateStr => {  
                const date = new Date(dateStr);  
                const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;  
                return formattedDate;  
            });  
        },
        handleModification(row) {
            if(this.multipleSelection == ''){
                return this.msgError('请勾选再操作')
            }
            this.$confirm(`是否确认手动发货，过程大概需要一分钟?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.loading = true
                    this.automatic_shippings()
                })
                .catch(() => {})
        },

        async automatic_shippings() {
            let response = await this.request.post(this.api.automatic_shipping, { 
                    ids:this.multipleSelection ,
                }
            )
            this.msgSuccess(response.msg)
            this.loading = false
            this.getList()
        },
        handleStatus(tab) {
            this.pageInfo.page = 1
            this.queryParams.status = tab.name
            this.getList()
        },
        handleStatus2(tab) {
            this.pageInfo.page = 1
            this.queryParams.type = tab.name
            this.getList()
        },
        resetSort() {
            
        },
        handleSortChange({ column, prop, order }) {
            // this.resetSort()
            // this.queryParams[prop] = order === 'descending' ? 'desc' : order === 'ascending' ? 'asc' : undefined
            // this.getList()
        },
        showDetailDialog(row) {
            this.detailDialog.visible = true
            this.detailDialog.data = row
        },
        showDetailDialog2(row) {
            this.detailDialog2.visible = true
            this.detailDialog2.data = row
        },
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.created_time?.length == 2) {
                qyparams.created_time = [parseTime(qyparams.created_time[0], 'y-m-d'), parseTime(qyparams.created_time[1], 'y-m-d')]
            }
            exportAutoshipping(qyparams)
                .then(res => {
                    exportFile(res, () => {
                        this.download = false
                    })
                })
                .catch(err => {
                    console.log(err)
                    this.download = false
                })
        },
        downloadExcel() {
            window.open(this.downloadUrl, '_blank')
        },
        handleClick() {
            this.getList()
        },

        //列表
        getList() {
            this.multipleSelection = [];
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
                
            if (qyparams.created_time?.length == 2) {
                qyparams.created_time = [parseTime(qyparams.created_time[0], 'y-m-d'), parseTime(qyparams.created_time[1], 'y-m-d')]
            }
            queryAutoshipping(qyparams)
                .then(response => {
                    this.tableData = response.data.list
                    this.total = response.data.total
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')
            this.resetSort()
            this.$refs.sortTable.clearSort()
            this.handleQuery()
        },

    },
}
</script>
<style lang="scss" scoped>
.total-warp {
    font-size: 18px;
    font-weight: bold;
    padding: 8px 0 16px 0;
}
    /* 统计卡片 */
    .chart-card {
        color: #606266;
        margin: 10px 0;
    }
    .chart-card-num {
        font-size: 30px;
    }

    .chart-card-content {
        height: 30px;
        .content-title {
            font-weight: bold;
            font-size: 20px;
            color: #303133;
        }
    }
</style>
